<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class GiftBagIntimacyLog extends Base
{
    protected $table = 'gift_bag_intimacy_log';
    const REDIS_INTIMACY_NAME = 'INTIMACYVALUE:';//亲密值
    const REDIS_SEND_RANK_NAME = 'SENDRANKLIST:'; //送礼榜
    const REDIS_COLLECT_RANK_NAME = 'COLLECTRANKLIST:';//收礼榜

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }


    /*
         * 获取用户cp
         * @param [$user_id]   用户id
         * */
    public function getCpUser($to_user)
    {
        $data = DB::connection("mysql_kkaudio")
            ->table("coupling")
            ->whereIn('user_id', $to_user)
            ->select(['user_id', 'cp_user_id'])->get();
        return self::objToArray($data);
    }


    public function create($cp, $num = 1)
    {
        $value = $num * 5;
        $all_intimacy = 5000 - $value;
        foreach ($cp as $v) {
            $user_intimacy = Redis::hget(self::REDIS_INTIMACY_NAME . $v['user_id'], 'value') ?? 0;
            if ($user_intimacy > $all_intimacy) {
                $value = 5000 - $user_intimacy;
            }
            $v['intimate'] = $value / 5;
            if ($value == 0) {
                write_log('intimacyValueConsumer', 'cpIntimacyTopError', json_encode($v));//亲密值赠送失败
                continue;
            }
            $pearl_api = json_decode(curl_request(env('KK_API_HOST') . '/coupling/activity/intimate/incr', $v, 'urlencoded', 'GET'), true);
            if ($pearl_api['code'] !== 0) {
                //充值失败
                write_log('intimacyValueConsumer', 'couplingApiError', json_encode($v));//亲密值赠送失败
                return false;
            }
            Redis::hincrby(self::REDIS_INTIMACY_NAME . $v['user_id'], 'value', $value);
        }
        return true;
    }


    //送礼 收礼 排行榜
    public function rankList($user_id, $to_user, $num = 1)
    {

        $send_name = self::REDIS_SEND_RANK_NAME;
        $collect_name = self::REDIS_COLLECT_RANK_NAME;
        $count = $num * count($to_user);
        Redis::ZADD($send_name, Redis::hincrby($send_name . $user_id, 'rank', $count), $user_id);
        foreach ($to_user as $v) {
            Redis::ZADD($collect_name, Redis::hincrby($collect_name . $v, 'rank', $num), $v);
        }
        return true;
    }

    public function userIntimacy($user_id)
    {
        if (empty($user_id)) {
            return 0;
        }
        return Redis::hget(self::REDIS_INTIMACY_NAME . $user_id, 'value');
    }


    public function giftRank()
    {
        $send_rank = $this->chacheRankList(self::REDIS_SEND_RANK_NAME);
        $collect_rank = $this->chacheRankList(self::REDIS_COLLECT_RANK_NAME);
        $res['send_rank'] = $send_rank;
        $res['collect_rank'] = $collect_rank;
        return $res;
    }


    //获取有序集合排名
    public function chacheRankList($key)
    {
        return Redis::zrevrange($key, 0, 99);
    }

    //    获取有序集合排名&值/
    public function chacheRankListToValue($key)
    {
        return Redis::zrevrange($key, 0, 99, 'WITHSCORES');
    }

    public function giveUserApi($data, $api_data)
    {
        $api_data['user_id'] = $data['user_id'];
        $api = json_decode(curl_request(env('KK_API_HOST') . '/mall/goods/give_user', $api_data), true);
        $api_data['type'] = $data['type'];
        if ($api['code'] !== 0) {
            //充值失败
            $api_data['apiMsg'] = $api['msg'];
            write_log('giftRankAward', 'giveGiftError', json_encode($api_data));
            return false;
        }
        $this->createSendGoodsLog($api_data);
        return true;
    }


    public function createSendGoodsLog($api_data)
    {
        $data['user_id'] = $api_data['user_id'];
        $data['goods_id'] = $api_data['goods_id'];
        $data['goods_type'] = $api_data['goods_type'];
        $data['time_limit'] = $api_data['time_limit'];
        $data['goods_status'] = 0;
        $data['send_type'] = $api_data['type'] + 1; // 2送礼 3收礼
        $data['created_at'] = $data['updated_at'] = date_ymd();
        $res = DB::table('share_send_goods')->insertGetId($data);
        if (!$res)
            return false;
        return $res;
    }


    public function sendMsgApi($data, $msg)
    {
        $msg_data_mount['user_id'] = $data['user_id'];

        $msg_data_mount['msg'] = $msg;
        $api = json_decode(curl_request(env('KK_API_HOST') . '/msg/text', $msg_data_mount), true);
        if ($api['code'] !== 0) {
            //充值失败
            $msg_data_mount['apiMsg'] = $api['msg'];
            $msg_data_mount['type'] = $data['type'];
            write_log('giftRankAward', 'msgError', json_encode($msg_data_mount));
            return false;
        }
        return true;
    }

    public function awardPearlApi($dataArr, $award_pearl)
    {
        $data['user_id'] = $dataArr['user_id'];
        $data['pearl_num'] = $award_pearl;
        $data['msg'] = '榜单奖励金豆';
        $api = json_decode(curl_request(env('KK_API_HOST') . '/finance/pearl/recharge', $data), true);
        if ($api['code'] !== 0) {
            //充值失败
            $data['apiMsg'] = $api['msg'];
            $data['type'] = $dataArr['type'];
            write_log('giftRankAward', 'pearlApiError', json_encode($data));
            return false;
        }
        return true;
    }

    //排行榜补发
    public function checkVaule($time)
    {
        $data = $this->timeToUserGift($time, 'gift_stream', 89); //壁咚礼物补差
        $from_user = array_unique(array_column($data, 'from_user_id'));//送用户
        $user_id = array_unique(array_column($data, 'user_id'));//收用户
        $send_name = self::REDIS_SEND_RANK_NAME; // 送
        $collect_name = self::REDIS_COLLECT_RANK_NAME;//收
        $from_user_value = [];//用户送礼数量
        $user_value = [];//用户收礼数量
        foreach ($data as $v) {
            foreach ($from_user as $vv) {
                if (empty($from_user_value[$vv]['gift_num'])) $from_user_value[$vv]['gift_num'] = 0;
                if (empty($from_user_value[$vv]['rank_num'])) $from_user_value[$vv]['rank_num'] = 0;
                if ($v['from_user_id'] == $vv) {
                    $from_user_value[$vv]['gift_num'] += $v['gift_num'];
                    $from_user_value[$vv]['rank_num']++;//已送名次积分
                }
            }
            foreach ($user_id as $val) {
                if (empty($user_value[$val]['gift_num'])) $user_value[$val]['gift_num'] = 0;
                if (empty($user_value[$val]['rank_num'])) $user_value[$val]['rank_num'] = 0;
                if ($v['user_id'] == $val) {
                    $user_value[$val]['gift_num'] += $v['gift_num'];
                    $user_value[$val]['rank_num']++;
                }
            }
        }
        //送
        foreach ($from_user_value as $k => $v) {
            $send_num = Redis::hget($send_name . $k, 'rank');
            if (!$send_num) {
                continue; //用户送礼榜为空
            }
            $num =  $v['gift_num']; // 所的积分
            //清空集合原有数据
            Redis::ZREM($send_name, $k);
            //重新赋新值
            Redis::hmset($send_name . $k, 'rank', $num);
            $new_num = Redis::hget($send_name . $k, 'rank');
//            集合加入新值
            Redis::ZADD($send_name, $new_num, $k);
        }
        //收
        foreach ($user_value as $key => $val) {
            $collect_num = Redis::hget($collect_name . $key, 'rank');
            if (!$collect_num) {
                continue; //用户送礼榜为空
            }
            $num = $val['gift_num']; // 所的积分
            //清空集合原有数据
            Redis::ZREM($collect_name, $key);
            //计算后重新赋值
            Redis::hmset($collect_name . $key, 'rank', $num);
            $new_collect_num = Redis::hget($collect_name . $key, 'rank');
            //集合加入新值
            Redis::ZADD($collect_name, $new_collect_num, $key);
        }
        return true;//更新完成；
    }

    public function getRankListRedis()
    {
        $send_name = self::REDIS_SEND_RANK_NAME; // 送
        $collect_name = self::REDIS_COLLECT_RANK_NAME;//收
        $data[] = $this->chacheRankListToValue($send_name);
        $data[] = $this->chacheRankListToValue($collect_name);
        return $data;
    }


    public function updateIntimacy($time)
    {
        $data = $this->timeToUserGift($time, 'gift_pearl_stream', 35);
        $user_id = array_unique(array_column($data, 'user_id'));//收用户
        $checkCp = $this->getCpUser($user_id);
        if (!$checkCp) {
            return false;
        }
        $user_value = [];//用户收数量  & 总亲密值
        foreach ($data as $v) {
            foreach ($checkCp as $val) {
                if (empty($user_value[$val['user_id']]['gift_num'])) $user_value[$val['user_id']]['gift_num'] = 0;
                if (empty($user_value[$val['user_id']]['intimacy_value'])) $user_value[$val['user_id']]['intimacy_value'] = 0;
                if ($v['user_id'] == $val['user_id']) {
                    $user_value[$val['user_id']]['gift_num'] += $v['gift_num'];
                    $user_value[$val['user_id']]['cp_user_id'] = $val['cp_user_id'];
                    $user_value[$val['user_id']]['intimacy_value']++;
                }
            }
        }
        foreach ($user_value as $k => $v) {
            $score = $v['gift_num'] * 5;
            if ($v['gift_num'] > 1000) {
                $v['gift_num'] = 1000;//积分上限
                $score = 5000;
            } else {
                $d['user_id'] = $k;
                $d['cp_user_id'] = $v['cp_user_id'];
                $d['intimate'] = $v['gift_num'] - $v['intimacy_value']; // 需要 补发亲密值
                if($d['intimate'] != 0){
                    $pearl_api = json_decode(curl_request(env('KK_API_HOST') . '/coupling/activity/intimate/incr', $d, 'urlencoded', 'GET'), true);
                    if ($pearl_api['code'] !== 0) {
                        //充值失败
                        write_log('newIntimacy', 'newCouplingApiError', $data);//亲密值赠送失败
                    }
                }
            }
            Redis::hmset(self::REDIS_INTIMACY_NAME . $k, 'value', $score);
        }
        return true;
    }


    public function timeToUserGift($time, $table, $gift_id)
    {
        $res = $data = DB::connection("mysql_kkaudio")
            ->table($table)
            ->where(['gift_id' => $gift_id])
            ->whereBetween('change_timestamp', $time)
            ->get();
        return json_decode($res, true);
    }

    //差价log 库 type ; 1送礼榜 2 收礼 3 积分 4亲密值
    public function creaeteLog($user_id, $type, $old_num, $new_num)
    {
        $data['user_id'] = $user_id;
        $data['type'] = $type;
        $data['old_num'] = $old_num;
        $data['new_num'] = $new_num;
        $data['created_at'] = $data['updated_at'] = date_ymd();
        $res = DB::table('gift_bag_edit_score_intimacy_log')->insert($data);
        if (!$res) {
            write_log('newIntimacy', 'createLogError', $data);//积分日志赠送失败
        }
        return true;
    }


}